<?php
require_once __DIR__ . '/includes/functions.php';

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $title = sanitize_input($_POST['title']);
        $content = sanitize_input($_POST['content'], true); // Preserve HTML
        $format = sanitize_input($_POST['format']);
        
        if (empty($title) || empty($content)) {
            throw new Exception('标题和内容不能为空');
        }

        $filename = create_post($title, $content, $format);
        $success = "文章创建成功！<a href='/?route=post&file=$filename'>查看文章</a>";
    } catch (Exception $e) {
        $error = '错误：' . $e->getMessage();
        error_log('创建文章失败：' . $e->getMessage());
        error_log('POST 数据：' . print_r($_POST, true));
        error_log('文件路径：' . POSTS_DIR . '/' . date('Y-m-d') . '-' . strtolower(str_replace(' ', '-', $title)) . '.' . $format);
    }
}

render_template('header', ['title' => '创建新文章']);
?>

<h1>创建新文章</h1>

<?php if ($error): ?>
    <div class="error"><?= $error ?></div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="success"><?= $success ?></div>
<?php endif; ?>

<form method="POST">
    <div>
        <label for="title">标题：</label>
        <input type="text" id="title" name="title" required>
    </div>
    
    <div>
        <label for="content">内容：</label>
        <textarea id="content" name="content" rows="10" required></textarea>
    </div>
    
    <div>
        <label for="format">格式：</label>
        <select id="format" name="format">
            <option value="html">HTML</option>
            <option value="md">Markdown</option>
            <option value="txt">纯文本</option>
        </select>
    </div>
    
    <button type="submit">创建文章</button>
</form>

<?php
render_template('footer');
?>
